package com.zat.mes.andrmes.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.love.zywanandroid.retrofit.RetrofitManager;
import com.love.zywanandroid.retrofit.api.ApiService;
import com.zat.mes.andrmes.BomNotifiBean;
import com.zat.mes.andrmes.MachineWarnNotifiBean;
import com.zat.mes.andrmes.R;
import com.zat.mes.andrmes.data.BaseResponse;
import com.zat.mes.andrmes.data.DayPlanNotifBean;
import com.zat.mes.andrmes.data.Item;
import com.zat.mes.andrmes.data.MessageBean;
import com.zat.mes.andrmes.dofun.BomNotifiActivity;
import com.zat.mes.andrmes.dofun.MachineWarnNotifiActivity;
import com.zat.mes.andrmes.dofun.MessageListActivity;
import com.zat.mes.andrmes.dofun.main.NotificationActivity;
import com.zat.mes.andrmes.utils.ActivityUtils;
import com.zat.mes.andrmes.utils.DateUtil;
import com.zat.mes.andrmes.utils.PreferencesUtil;

import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Response;

public class PollService extends Service {

    private static final String CHANNEL_ID_STRING = "ntl1010";
    private static final String CHANNEL_ID_NOTI = "ntl1011";
    private TimerTask task;
    private Timer timer;
    private int recode = 111;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Intent intent = null;
            PendingIntent pIntent= null;
            String content = "";
            switch (msg.what){
                case 0://日计划
                   intent = new Intent(getApplicationContext(), NotificationActivity.class);
                    ArrayList<DayPlanNotifBean> dayPlanNotifBeans = (ArrayList<DayPlanNotifBean>) msg.obj;
                    intent.putExtra("dayPlanList",dayPlanNotifBeans);
                    pIntent = PendingIntent.getActivity(getApplicationContext(), recode,
                            intent, PendingIntent.FLAG_CANCEL_CURRENT);
                    DayPlanNotifBean dayPlanNotifBean = dayPlanNotifBeans.get(0);
                    switch (dayPlanNotifBean.getStatus()){
                        case "1":
                            content = "日计划"+dayPlanNotifBean.getPlanDayNumber()+"暂停";
                            break;
                        case "2":
                            content = "日计划"+dayPlanNotifBean.getPlanDayNumber()+"停止";
                            break;
                        case "3":
                            content = "日计划"+dayPlanNotifBean.getPlanDayNumber()+"开始";
                            break;
                    }
                    break;
                case 1://通知公告
                    ArrayList<Item> items = (ArrayList<Item>) msg.obj;
                    intent = new Intent(getApplicationContext(), MessageListActivity.class);
                    intent.putExtra("msgList",items);
                    pIntent = PendingIntent.getActivity(getApplicationContext(), recode,
                            intent, PendingIntent.FLAG_CANCEL_CURRENT);
                    content = "公告："+items.get(0).getTitle();
                    break;
                case 2://物料通知
                    ArrayList<BomNotifiBean> itemList = (ArrayList<BomNotifiBean>) msg.obj;
                    intent = new Intent(getApplicationContext(), BomNotifiActivity.class);
                    intent.putExtra("bomList",itemList);
                    pIntent = PendingIntent.getActivity(getApplicationContext(), recode,
                            intent, PendingIntent.FLAG_CANCEL_CURRENT);
                    content = "物料："+itemList.get(0).getProductName();
                    break;
                case 3://机器预警
                    ArrayList<MachineWarnNotifiBean> warnList = (ArrayList<MachineWarnNotifiBean>) msg.obj;
                    intent = new Intent(getApplicationContext(), MachineWarnNotifiActivity.class);
                    intent.putExtra("machineWarn",warnList);
                    pIntent = PendingIntent.getActivity(getApplicationContext(),recode,intent,PendingIntent.FLAG_CANCEL_CURRENT);
                    content = "机器预警："+warnList.get(0).getMachineName();
                    break;

            }
            NotificationManager nManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);

            Notification notification = null;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID_NOTI, "新天伦", NotificationManager.IMPORTANCE_HIGH);
                // 配置通知渠道的属性
                // 设置通知出现时声音，默认通知是有声音的
                mChannel.setSound(null, null);
                // 设置通知出现时的闪灯（如果 android 设备支持的话）
                mChannel.enableLights(true);
                mChannel.setLightColor(Color.RED);
                // 设置通知出现时的震动（如果 android 设备支持的话）
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

                nManager.createNotificationChannel(mChannel);
                mChannel.enableLights(true);
                notification = new Notification.Builder(
                        getApplicationContext(), CHANNEL_ID_NOTI)
                        .setContentTitle("新天伦")
                        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.mes_ntl_ico)
                        .setContentText(content)
                        .setTicker(content)
                        .setContentIntent(pIntent)
                        .build();
            } else {
                notification = new Notification.Builder(
                        getApplicationContext())
                        .setContentTitle("新天伦")
                        .setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setSmallIcon(R.drawable.mes_ntl_ico)
                        .setContentText(content)
                        .setTicker(content)
                        .setContentIntent(pIntent)
                        .build();


            }

            nManager.notify(recode, notification);
            recode = recode + 1;
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //适配8.0service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, "新天伦MES", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(1, notification);
        }
    }


    public static void startPollService(Context context,String empId) {
        Intent intent = new Intent(context, PollService.class);
        intent.putExtra("empId",empId);
        //开启服务兼容
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        Toast.makeText(this, "开启轮询", Toast.LENGTH_SHORT).show();
        if (task == null) {
            task = new TimerTask() {

                @Override
                public void run() {
                    if (ActivityUtils.has("com.zat.mes.andrmes.dofun.main.MainActivity")) {
                        try {
                            //日计划
                            Response<BaseResponse<ArrayList<DayPlanNotifBean>>> result = RetrofitManager.Companion.apiService(ApiService.class)
                                    .getDayPlanChangeSelect(intent.getStringExtra("empId")).execute();
                            if (result != null && result.body() != null && result.body().getResult() != null && result.body().getResult().size() > 0) {
                                Message message = Message.obtain();
                                message.obj = result.body().getResult();
                                message.what = 0;
                                handler.sendMessage(message);
                                //
                            }
                            //通知公告
                            Response<BaseResponse<ArrayList<Item>>> messageResult = RetrofitManager.Companion.apiService(ApiService.class)
                                    .getMessageNotifi(intent.getStringExtra("empId")).execute();
                            if (messageResult != null && messageResult.body() != null && messageResult.body().getResult() != null && messageResult.body().getResult().size()>0) {
                                Message message = Message.obtain();
                                message.obj = messageResult.body().getResult();
                                message.what = 1;
                                handler.sendMessage(message);
                                //
                            }
                            //bom 通知
                            String now = DateUtil.formatDate(new Date(),DateUtil.FORMAT_3);
                            String key = now+intent.getStringExtra("empId");
                            if (!PreferencesUtil.INSTANCE.getBoolean(key,false)) {
                                Response<BaseResponse<ArrayList<BomNotifiBean>>> bomResult = RetrofitManager.Companion.apiService(ApiService.class)
                                        .getBomNotifi(intent.getStringExtra("empId")).execute();
                                if (bomResult != null && bomResult.body() != null && bomResult.body().getResult() != null && bomResult.body().getResult().size() > 0) {
                                    Message message = Message.obtain();
                                    message.obj = bomResult.body().getResult();
                                    message.what = 2;
                                    handler.sendMessage(message);
                                    //
                                }
                                PreferencesUtil.INSTANCE.saveValue(key,true);
                            }
                            //机器预警
                            Response<BaseResponse<ArrayList<MachineWarnNotifiBean>>> machineWarn = RetrofitManager.Companion.apiService(ApiService.class)
                                    .getMachineWarn(intent.getStringExtra("empId")).execute();
                            if (machineWarn != null && machineWarn.body() != null && machineWarn.body().getResult() != null && machineWarn.body().getResult().size()>0) {
                                Message message = Message.obtain();
                                message.obj = machineWarn.body().getResult();
                                message.what = 3;
                                handler.sendMessage(message);
                                //
                            }


                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }else{
                        Log.i("PollService", "stop");
                        stopSelf();
                    }
                }
            };
        }
        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(task, 1 * 1000, 60 * 1000);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 取消任务
     */
    private void cancelTask() {
        if (task != null && timer != null) {
            task.cancel();
            timer.cancel();
            task = null;
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        if (task != null && timer != null) {
            cancelTask();
        }
        super.onDestroy();
    }
}
